package com.wmx.thread.synchronize_and_lock;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**********************************
 * @author wmx
 * @date 2019/8/20 17:44
 * @description:
 * @version 1.0
 * 如果有一个线程已经占用了读锁，则此时其他线程如果要申请写锁，则申请写锁的线程会一直等待释放读锁。
 * 如果有一个线程已经占用了写锁，则此时其他线程如果申请写锁或者读锁，则申请的线程会一直等待释放写锁。
 *
 ************************************/
public class ReadAndWritLockTest {

    ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    public static void main(String[] args) {

        ReadAndWritLockTest readAndWritLockTest = new ReadAndWritLockTest();
        new Thread(()->{
            readAndWritLockTest.read(Thread.currentThread());
        }).start();
        new Thread(()->{
            readAndWritLockTest.read(Thread.currentThread());
        }).start();
       /* new Thread(()->{
            readAndWritLockTest.insert(Thread.currentThread());
        }).start();*/
    }

    //写操作

    public void insert(Thread thread){

        Long start = System.currentTimeMillis();
        reentrantReadWriteLock.writeLock().lock();
        try {
            while (System.currentTimeMillis() -start <=1){
                System.out.println(thread.getName()+"正在进行写操作");
            }
            System.out.println(thread.getName()+"写操作完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantReadWriteLock.writeLock().unlock();

        }
    }


    //读操作
    public void read(Thread thread){
        System.out.println(thread.getName()+"获得锁");
        reentrantReadWriteLock.readLock().lock();
        /*Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
        System.out.println("时间字符串【yyyy-MM-dd】："+retStrFormatNowDate);*/
        Long start = System.currentTimeMillis();
        try {
            while (System.currentTimeMillis() -start <=100){
                System.out.println(thread.getName()+"正在进行读操作");
            }
            System.out.println(thread.getName()+"读操作完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantReadWriteLock.readLock().unlock();
        }
    }

}
